package com.woniuxy.intellihome.controller.admin;


import com.woniuxy.intellihome.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Hw 0812 11:49 增加category的add,list方法
 * @since 2021-08-11
 */
@RestController
@Slf4j
@RequestMapping("/admin/picture")
public class PictureController {
    @Autowired
    private CategoryService categoryService;

    @Value("${IntelliHome.images}")
    private String imagePath;

    @RequestMapping("test")
    public String test(){
        return "ok";
    }

    @RequestMapping("getpath")
    @ResponseBody
    public String getPath(HttpServletRequest request){
        String contextPath = request.getServletContext().getContextPath();
        return contextPath;
    }

    /**
     * 上传数据文件
     *
     * @author : lichenfei
     * @date : 2018年11月22日
     * @time : 下午2:46:29
     * @return @
     */
    @RequestMapping("upload")
    @ResponseBody
    public Map<String, Object> uploadToUser(@RequestParam("file") MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        FileOutputStream out = null;
        try {
            String fileName = file.getOriginalFilename();
            if (fileName.indexOf("\\") != -1) {
                fileName = fileName.substring(fileName.lastIndexOf("\\"));
            }
            // 获取文件存放地址
            log.debug("存放路径{}",imagePath);
            String filePath = imagePath;
            File f = new File(filePath);
            if (!f.exists()) {
                f.mkdirs();// 不存在路径则进行创建
            }
            // 重新自定义文件的名称
            filePath = filePath + fileName;
            out = new FileOutputStream(filePath);
            out.write(file.getBytes());
            out.flush();
            out.close();
            map.put("1", "ok");
            Thread.sleep(10000);
            return map;
        } catch (Exception e) {
            map.clear();
            map.put("2", "error");
            return map;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

